package common

import (
	"encoding/json"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/backend_controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	common3 "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/common"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/common"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type FileController struct {
	backend_controller.BackendBaseController
	fileService common.FileSerivceIface
}

func NewFileController(fileService common.FileSerivceIface) *FileController {
	return &FileController{fileService: fileService}
}

func (c *FileController) RegisterRouter(g *gin.RouterGroup) {
	// 获取oss签名
	g.POST("/common/file/get-oss-signature", c.GetOssSignature)
	// 保存图片/文件信息
	g.POST("/common/file/save-file-info", c.SaveFileInfo)
}

func (c *FileController) GetOssSignature(ctx *gin.Context) {
	var params = make(map[string]interface{})
	err := json.NewDecoder(ctx.Request.Body).Decode(&params)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, "参数有误"+err.Error())
		return
	}
	business, _ := params["business"].(string)
	if business == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "business 不能为空")
		return
	}
	if _, ok := constants.FileBusinessTypes[business]; !ok {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "非法 business type")
		return
	}

	// 存储到文件表
	policyToken, err := c.fileService.GetPolicyToken(ctx, business, "")
	if err != nil {
		c.Fail(ctx, ykerrcode.FAIL, err.Error())
		return
	}
	c.Success(ctx, policyToken)
}

func (c *FileController) SaveFileInfo(ctx *gin.Context) {
	req := common3.SaveFileInfoRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		stark.Logger.Errorf(ctx.Request.Context(), "SaveFileInfo 参数错误:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, "参数不合法 "+err.Error())
		return
	}
	isPrivate := int64(1)
	fileUid, err := c.fileService.SaveToFile(ctx, req.FilePath, req.FileType, req.FileName, req.Business, req.FileSize, isPrivate, "")
	if err != nil {
		c.Fail(ctx, ykerrcode.FAIL, err.Error())
		return
	}
	if fileUid == "" {
		c.Fail(ctx, ykerrcode.FAIL, "文件id获取不到")
		return
	}
	saveFileInfoResponse := &common3.SaveFileInfoResponse{
		Uid: fileUid,
	}
	c.Success(ctx, saveFileInfoResponse)
}
